package com.eatwhat.service;

import com.eatwhat.dto.PageResult;
import com.eatwhat.entity.Food;
import com.eatwhat.mapper.FoodMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Random;

@Service
public class FoodService {
    
    @Autowired
    private FoodMapper foodMapper;
    
    private Random random = new Random();
    
    public PageResult<Food> getFoodsByPage(int page, int size) {
        int offset = (page - 1) * size;
        List<Food> foods = foodMapper.findByPage(offset, size);
        long total = foodMapper.countTotal();
        return new PageResult<>(foods, total, size, page);
    }
    
    public List<Food> getAllEnabledFoods() {
        return foodMapper.findAllEnabled();
    }
    
    public Food getFoodById(Long id) {
        return foodMapper.findById(id);
    }
    
    public List<Food> getFoodsByCategory(Long categoryId) {
        return foodMapper.findByCategoryId(categoryId);
    }
    
    public Food saveFood(Food food) {
        if (food.getId() == null) {
            if (food.getStatus() == null) {
                food.setStatus(1);
            }
            if (food.getWeight() == null) {
                food.setWeight(1);
            }
            foodMapper.insert(food);
        } else {
            foodMapper.update(food);
        }
        return food;
    }
    
    public void deleteFood(Long id) {
        foodMapper.deleteById(id);
    }
    
    public List<Food> searchFoods(String keyword) {
        return foodMapper.searchByKeyword(keyword);
    }
    
    /**
     * 随机选择一个菜品
     */
    public Food getRandomFood() {
        List<Food> enabledFoods = foodMapper.findAllEnabled();
        if (enabledFoods.isEmpty()) {
            return null;
        }
        
        // 根据权重进行随机选择
        int totalWeight = enabledFoods.stream().mapToInt(Food::getWeight).sum();
        int randomWeight = random.nextInt(totalWeight) + 1;
        
        int currentWeight = 0;
        for (Food food : enabledFoods) {
            currentWeight += food.getWeight();
            if (randomWeight <= currentWeight) {
                return food;
            }
        }
        
        // 如果没有找到，返回第一个
        return enabledFoods.get(0);
    }
}